package com.gp.billsrecord.ui.common

import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.CheckedTextView
import android.widget.TextView
import androidx.core.view.setPadding
import androidx.fragment.app.viewModels
import com.google.android.flexbox.FlexboxLayout
import com.gp.billsrecord.base.BaseBottomSheetDialog
import com.gp.billsrecord.databinding.FragmentFilterSelectBinding
import com.gp.billsrecord.model.data.ConsumptionType
import com.gp.billsrecord.vm.AppViewModel

/**
 * 条件筛选
 */
class FilterSelectDialog : BaseBottomSheetDialog<FragmentFilterSelectBinding>() {
    private val viewModel by viewModels<AppViewModel>()

    override fun onBindingCreated() {
        binding.btnSaveTagFilter.setOnClickListener {
            //保存筛选条件
            val tags = binding.tagBox.obtainChildTags()
            dismiss()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewModel.observeConsumptionTypes().observe(viewLifecycleOwner) {
            binding.tagBox.addTags(it)
        }
    }
}

private fun FlexboxLayout.obtainChildTags(): List<Long> = ArrayList<Long>().apply {
    for (i in 0 until childCount) {
        val child = getChildAt(i) as CheckedTextView
        if (child.isChecked) {
            add(child.tag as Long)
        }
    }
}


private fun FlexboxLayout.addTags(list: List<ConsumptionType>) {
    list.forEach {
        addView(createTextView(it, context))
    }
}

fun createTextView(type: ConsumptionType, context: Context): View = CheckedTextView(context).apply {
    text = type.typeName
    tag = type.typeId
    setPadding(20)
}
